using Lzfy_His_Service.Models;
using Oracle.ManagedDataAccess.Client;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper;

namespace Lzfy_His_Service.Services
{
    /// <summary>
    /// 在院病人查询服务实现
    /// </summary>
    public class InpatientService : IInpatientService
    {
        private readonly IOracleConnectionFactory _oracleConnectionFactory;
        private readonly ILogger<InpatientService> _logger;

        public InpatientService(
            IOracleConnectionFactory oracleConnectionFactory,
            ILogger<InpatientService> logger)
        {
            _oracleConnectionFactory = oracleConnectionFactory;
            _logger = logger;
        }

        /// <summary>
        /// 查询在院病人列表
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns>在院病人列表</returns>
        public async Task<List<InpatientInfo>> GetInpatientListAsync(InpatientListRequest request)
        {
            try
            {
                _logger.LogInformation("开始查询在院病人列表，科室代码: {CurrentWard}, 医院区域: {HospitalArea}", 
                    request.CurrentWard, request.HospitalArea);

                using var connection = _oracleConnectionFactory.CreateConnection();
                
                var sql = @"
                    SELECT t1.bed_code as BedCode,
                           t1.patient_name as PatientName,
                           t1.patient_id as PatientId,
                           t1.visit_id as VisitId,
                           t1.patient_age_string as PatientAgeString,
                           to_char(t1.admission_date, 'yyyy-mm-dd hh24:mi:ss') as AdmissionDate,
                           t2.people_name as DoctorChief,
                           t1.pai_visit_id as PaiVisitId
                      FROM pts.pai_visit t1
                      JOIN uum.uum_user t2
                        ON t1.doctor_chief = t2.user_name
                     WHERE t1.current_ward = :currentWard
                       AND t1.in_flag = '0'
                       AND t1.hospital_area = :hospitalArea
                     ORDER BY t1.bed_code, t1.patient_id";

                var parameters = new
                {
                    currentWard = request.CurrentWard,
                    hospitalArea = request.HospitalArea
                };

                var result = await connection.QueryAsync<InpatientInfo>(sql, parameters);
                var inpatientList = result.ToList();

                _logger.LogInformation("在院病人列表查询完成，科室代码: {CurrentWard}，查询到 {Count} 条记录", 
                    request.CurrentWard, inpatientList.Count);

                return inpatientList;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "在院病人列表查询失败，科室代码: {CurrentWard}, 医院区域: {HospitalArea}", 
                    request.CurrentWard, request.HospitalArea);
                throw;
            }
        }
    }
}